import axios from 'axios';
import {shim} from 'promise.prototype.finally';
import md5 from 'blueimp-md5';
import { getLogin } from '@/utils/auth';
import qs from 'qs';
import store from '@/store';
import Notification from '@/element-ui/packages/notification';
import router from "@/routers/app.routers";
import { getUUID } from "@/utils/uuid";

shim();

const axiosInstance = axios.create({
  baseURL: window.location.origin,
  timeout: 5000,
});

const debouncedLogout = _.debounce((data) => {
  if (data.code === code.KICK) {
    Notification.error('您的账号已在别处登录');
  } else {
    Notification.error(data.message);
  }
  store.dispatch(types.LOGOUT);
}, 1000);

const handleResponse = ({type, url, data}) => {
  if (data.code === code.FORBIDDEN) {
    // router.push({name: 'forbidden'});
    window.location.href = '/forbidden.html';
    return [false, data];
  } else if (data.code === 1 || data.errno === 0) {
    // console.log('request api post result:', `/api${url}`, data);
    return [true, data.data];
  } else if (data && _.isEmpty(data)) {
    return [false, undefined];
  } else if (data && _.isUndefined(data.code) && !data.errno) {
    return [true, data ? data.data : undefined];
  } else if (data.code === code.EXPIRE || data.code === code.KICK) {
    //退出登录到login
    debouncedLogout(data);

    return [false, data];
  } else {
    // Notification.error(data.message);
    return [false, data];
  }
};

const handelError = (err) => {
  if (err.message.indexOf('Network Error') !== -1) {
    err.message = '网络异常，请检查网络是否正确。';
  }

  return [false, err];
};

export async function get(url, params = {}, options = {}) {
  params = _addCommonParams(params);

  try {
    let resp;
    if (url.indexOf('http') !== -1) {
      resp = await axiosInstance.get(url, {params});
    } else {
      resp = await axiosInstance.get(`/api${url}`, {params});
    }
    let data = resp.data;
    // console.log(data);
    return handleResponse({
      type: 'get',
      url,
      data
    });
  } catch (err) {
    return handelError(err);
  }
}

export async function post(url, params = {}, options = {}) {
  // params = _addCommonParams(params)
  const signParams = _addSign();

  // 如果登录了，就再头信息里添加id,token
  const {token, uid} = getLogin();
  if (token) {
    signParams['token'] = token;
    signParams['uid'] = uid;
  }
  _setAxiosHeader(signParams);

  try {
    let resp;
    if (url.indexOf('http') !== -1) {
      resp = await axiosInstance.post(url, qs.stringify(params, {allowDots: true}));
    } else {
      resp = await axiosInstance.post(`/api${url}`, qs.stringify(params, {allowDots: true}));
    }

    // console.log(resp)
    let data = resp.data;

    return handleResponse({
      type: 'post',
      url,
      data
    });
  } catch (err) {
    return handelError(err);
  }
}


function _addCommonParams(params) {
  params = params ? params : {};

  return params;
}

function _addSign() {
  const timestamp = Date.parse(new Date());
  const signParams = {};
  signParams['device-id'] = getUUID();
  signParams['os-type'] = 0;
  signParams['timestamp'] = timestamp;
  signParams['version'] = '1.0';
  const urlStr = urlEncode(signParams).substr(1);
  signParams['sign'] = md5(urlStr + 'global');
  signParams['app-type'] = 2;
  return signParams;
}

function _setAxiosHeader(headers) {
  delete axios.defaults.headers.common.uid;
  delete axios.defaults.headers.common.token;
  const axiosCommom = axios.defaults.headers.common || {};
  axios.defaults.headers.common = Object.assign(axiosCommom, headers);
}

function urlEncode(param, key, encode) {
  if (param == null) return '';
  var paramStr = '';
  var t = typeof (param);
  if (t == 'string' || t == 'number' || t == 'boolean') {
    paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
  } else {
    for (var i in param) {
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
}
